package com.mgm.controller;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.mgm.advertisement.service.AdvertisementService;
import com.mgm.advertiser.service.AdvertiserService;
import com.mgm.conversion.service.ConversionService;
import com.mgm.dto.ConsumeCapDto;
import com.mgm.exception.CustomException;
import com.mgm.page.DataGrid;
import com.mgm.pojo.Advertisement;
import com.mgm.pojo.Advertiser;
import com.mgm.result.IMessage;
import com.mgm.result.IResult;


/**
 * Offer广告 Controller
 * <p>Title: AdvertiserController</p>
 * <p>Description: </p>
 * <p>Company: MGM</p> 
 * @author	Andy
 * @date	2018年6月20日上午10:52:43
 * @version 1.0
 */
@Controller
@RequestMapping("/advertisement")
public class AdvertisementController {
	
	private static Logger logger =LoggerFactory.getLogger(AdvertisementController.class);
	
	@Autowired
	private AdvertiserService advertiserService;
	@Autowired
	private AdvertisementService advertisementService;
	@Autowired
	private ConversionService conversionService;
	
	@RequestMapping(method = RequestMethod.GET)
	public ResponseEntity<IResult<DataGrid>> listAdvertisement(@RequestParam(value="page", defaultValue="1") Integer pageNum,
			@RequestParam(value="ps", defaultValue="10") Integer pageSize, @RequestParam(value="advName",required=false) String advName,
			@RequestParam(value="offerId",required=false) String offerId, @RequestParam(value="offerName",required=false) String offerName,
			@RequestParam(value="pkgName",required=false) String pkgName, @RequestParam(value="country",required=false) String country, 
			@RequestParam(value="enabled",required=false) String enabled, 
			HttpServletRequest request, HttpServletResponse response) {
		List<Advertiser> list = advertiserService.findByNameLike(advName);
		String advids = "";
		if(!CollectionUtils.isEmpty(list)) {
			for (Advertiser advertiser : list) {
				advids += advertiser.getId()+",";
			}
		}
		Map<String, String> map = new HashMap<>();
		map.put("advId", advids); //广告主
		map.put("offerId", offerId); //offerId
		map.put("offerName", offerName); //offerName
		map.put("pkgName", pkgName); //包名
		map.put("country", country); //国家
		map.put("enabled", enabled); //是否开启
		DataGrid dg = advertisementService.findAll(map, pageNum, pageSize);
		IResult<DataGrid> result = IResult.success(dg);
		
		return new ResponseEntity<IResult<DataGrid>>(result, HttpStatus.OK);
	}
	
	/**
	 * 
	 * @Title: createAdvertisement  
	 * @Description: 添加广告
	 * @param: @param advertisement
	 * @param: @return      
	 * @return: ResponseEntity<IMessage>      
	 * @throws
	 */
	@RequestMapping(method = RequestMethod.POST) 
	public ResponseEntity<IMessage> createAdvertisement(@RequestBody Advertisement advertisement){
		Advertiser advertiser = advertiserService.selectById(advertisement.getAdv_id()); //查询广告主
		if(advertiser==null) {
			throw new CustomException("该广告主不存在，请检查数据合法性");
		}
		IMessage msg = advertisementService.addAdvertisement(advertisement);
		return new ResponseEntity<IMessage>(msg, HttpStatus.CREATED);
	}
	
	@Deprecated
	@RequestMapping(value = "/{id}/icon", method = RequestMethod.POST) 
	public ResponseEntity<IMessage> uploadIcon(@PathVariable("id") Integer id,
			@RequestBody Map<String, String> map, 
			HttpServletRequest request, HttpServletResponse response){
		return null;
	}
	
	/**
	 * 
	 * @Title: getAdvertiser   
	 * @Description: 广告详情
	 * @param: @param id 广告id
	 * @param: @param ad_id 广告主id
	 * @param: @param request
	 * @param: @param response
	 * @param: @return      
	 * @return: ResponseEntity<IResult<Advertiser>>      
	 * @throws
	 */
	@RequestMapping(value = "/{id}/advertiser/{ad_id}", method = RequestMethod.GET)
	public ResponseEntity<IResult<Advertisement>> getAdvertiser(@PathVariable("id") Integer id,
			@PathVariable("ad_id") Integer ad_id, HttpServletRequest request, HttpServletResponse response) {
		IResult<Advertisement> res = advertisementService.selectByKeys(ad_id, id);
		return new ResponseEntity<IResult<Advertisement>>(res, HttpStatus.OK);
	}
	
	/**
	 * 
	 * @Title: updateAdvertisement   
	 * @Description: 修改广告信息 
	 * @param: @param advertisement
	 * @param: @return      
	 * @return: ResponseEntity<IMessage>      
	 * @throws
	 */
	@RequestMapping(method = RequestMethod.PUT) 
	public ResponseEntity<IMessage> updateAdvertisement(@RequestBody Advertisement advertisement){
		if(advertisement.getId()==null || advertisement.getAdv_id() == null) {
			logger.error("Illegal operation, Advertiser update fail!");
			throw new CustomException("非法操作，更新失败");
		}
		IMessage msg = advertisementService.updateAdvertisement(advertisement);
		return new ResponseEntity<IMessage>(msg, HttpStatus.OK);
	}
	
	/**
	 * 
	 * @Title: deleteAdvertisement   
	 * @Description: 删除广告  
	 * @param: @param id
	 * @param: @param ad_id
	 * @param: @param request
	 * @param: @param response
	 * @param: @return      
	 * @return: ResponseEntity<IMessage>      
	 * @throws
	 */
	@RequestMapping(value = "/{id}/advertiser/{ad_id}", method = RequestMethod.DELETE) 
	public ResponseEntity<IMessage> deleteAdvertisement(@PathVariable("id") Integer id,
			@PathVariable("ad_id") Integer ad_id, HttpServletRequest request, HttpServletResponse response) {
		Advertisement advertisement = advertisementService.selectById(id);
		if(advertisement==null) {
			logger.error("Unable to delete. Advertisement with id " + id + " not found");
			throw new CustomException("广告不存在，删除失败");
		}
		IMessage msg= advertisementService.deleteAdvertisement(ad_id, id);
		return new ResponseEntity<IMessage>(msg, HttpStatus.OK);
	}
	
	/**
	 * 
	 * @Title: enabled   
	 * @Description: 广告开关
	 * @param: @param id
	 * @param: @param map
	 * @param: @param request
	 * @param: @param response
	 * @param: @return      
	 * @return: ResponseEntity<IMessage>      
	 * @throws
	 */
	@RequestMapping(value = "/{id}/advertiser/{ad_id}/enabled", method = RequestMethod.PUT) 
	public ResponseEntity<IMessage> enabled(@PathVariable("id") Integer id, 
			@PathVariable("ad_id") Integer ad_id, @RequestBody Map<String, Boolean> map, 
			HttpServletRequest request, HttpServletResponse response) {
		Advertisement advertisement = advertisementService.selectById(id);
		if(advertisement==null) {
			logger.error("Unable to enabled. Advertisement with id " + id + " not found");
			throw new CustomException("广告不存在，操作失败");
		}
		if(advertisement.getAdv_id() != ad_id) {
			logger.error("Unable to enabled. Advertiser with Advertisement not equal");
			throw new CustomException("广告主与广告不匹配，操作失败");
		}
		if(map==null || map.get("enabled")==null) {
			logger.error("[Enabled Advertisement] Illegal operation");
			throw new CustomException("非法操作");
		}
		
		IMessage msg= advertisementService.isEnabled(id, map.get("enabled"));
		
		return new ResponseEntity<IMessage>(msg, HttpStatus.OK);
	}
	
	/**
	 * 
	 * @Title: premium   
	 * @Description: 修改广告溢价
	 * @param: @param id
	 * @param: @param ad_id
	 * @param: @param map
	 * @param: @param request
	 * @param: @param response
	 * @param: @return      
	 * @return: ResponseEntity<IMessage>      
	 * @throws
	 */
	@RequestMapping(value = "/{id}/advertiser/{ad_id}/premium", method = RequestMethod.PUT) 
	public ResponseEntity<IMessage> premium(@PathVariable("id") Integer id, 
			@PathVariable("ad_id") Integer ad_id, @RequestBody Map<String, Integer> map, 
			HttpServletRequest request, HttpServletResponse response) {
		Advertisement advertisement = advertisementService.selectById(id);
		if(advertisement==null) {
			logger.error("Unable to enabled. Advertisement with id " + id + " not found");
			throw new CustomException("广告不存在，操作失败");
		}
		if(advertisement.getAdv_id() != ad_id) {
			logger.error("Unable to enabled. Advertiser with Advertisement not equal");
			throw new CustomException("广告主与广告不匹配，操作失败");
		}
		if(map==null || map.get("premium")==null) {
			logger.error("[Premium Advertisement] Illegal operation");
			throw new CustomException("非法操作");
		}
		
		IMessage msg= advertisementService.modifyPremium(id, map.get("premium"));
		
		return new ResponseEntity<IMessage>(msg, HttpStatus.OK);
	}
	
	/**
	 * 
	 * @Title: restorePremium   
	 * @Description: 还原广告溢价
	 * @param: @param id
	 * @param: @param ad_id
	 * @param: @param request
	 * @param: @param response
	 * @param: @return      
	 * @return: ResponseEntity<IMessage>      
	 * @throws
	 */
	@RequestMapping(value = "/{id}/advertiser/{ad_id}/premium/clean", method = RequestMethod.PUT) 
	public ResponseEntity<IMessage> restorePremium(@PathVariable("id") Integer id, 
			@PathVariable("ad_id") Integer ad_id, 
			HttpServletRequest request, HttpServletResponse response) {
		Advertisement advertisement = advertisementService.selectById(id);
		if(advertisement==null) {
			logger.error("Unable to enabled. Advertisement with id " + id + " not found");
			throw new CustomException("广告不存在，操作失败");
		}
		if(advertisement.getAdv_id() != ad_id) {
			logger.error("Unable to enabled. Advertiser with Advertisement not equal");
			throw new CustomException("广告主与广告不匹配，操作失败");
		}
		
		IMessage msg= advertisementService.modifyInitialPremium(id);
		
		return new ResponseEntity<IMessage>(msg, HttpStatus.OK);
	}
	
	/**
	 * 
	 * @Title: updateCap   
	 * @Description: 修改广告cap
	 * @param: @param id
	 * @param: @param ad_id
	 * @param: @param map
	 * @param: @param request
	 * @param: @param response
	 * @param: @return      
	 * @return: ResponseEntity<IMessage>      
	 * @throws
	 */
	@RequestMapping(value="/{id}/advertiser/{ad_id}/cap", method = RequestMethod.PUT) 
	public ResponseEntity<IMessage> updateCap(@PathVariable("id") Integer id, 
			@PathVariable("ad_id") Integer ad_id, @RequestBody Map<String, BigDecimal> map, 
			HttpServletRequest request, HttpServletResponse response){
		Advertisement advertisement = advertisementService.selectById(id);
		if(advertisement==null) {
			logger.error("Unable to enabled. Advertisement with id " + id + " not found");
			throw new CustomException("广告不存在，操作失败");
		}
		if(advertisement.getAdv_id() != ad_id) {
			logger.error("Unable to enabled. Advertiser with Advertisement not equal");
			throw new CustomException("广告主与广告不匹配，操作失败");
		}
		IMessage msg= advertisementService.modifyCaps(id, map.get("total"), map.get("daily"));
		return new ResponseEntity<IMessage>(msg, HttpStatus.OK);
	}
	
	@RequestMapping(value="/{id}/advertiser/{ad_id}/cap/clean", method = RequestMethod.PUT) 
	public ResponseEntity<IMessage> restoreCap(@PathVariable("id") Integer id, 
			@PathVariable("ad_id") Integer ad_id,
			HttpServletRequest request, HttpServletResponse response){
		Advertisement advertisement = advertisementService.selectById(id);
		if(advertisement==null) {
			logger.error("Unable to enabled. Advertisement with id " + id + " not found");
			throw new CustomException("广告不存在，操作失败");
		}
		if(advertisement.getAdv_id() != ad_id) {
			logger.error("Unable to enabled. Advertiser with Advertisement not equal");
			throw new CustomException("广告主与广告不匹配，操作失败");
		}
		IMessage msg= advertisementService.modifyInitialCaps(id);
		return new ResponseEntity<IMessage>(msg, HttpStatus.OK);
	}
	
	/**
	 * 获取消耗Cap
	 * @Title: getCap   
	 * @Description: 总消耗、日消耗   
	 * @param: @param offerid
	 * @param: @param request
	 * @param: @param response
	 * @param: @return      
	 * @return: ResponseEntity<ConsumeCapDto>      
	 * @throws
	 */
	@RequestMapping(value = "/{offerid}/consumecap", method = RequestMethod.GET)
	public ResponseEntity<ConsumeCapDto> getCap(@PathVariable("offerid") String offerid,
			HttpServletRequest request, HttpServletResponse response) {
		ConsumeCapDto comCapDto = new ConsumeCapDto();
		comCapDto.setConsume_payout_cap(conversionService.selectTotalCap(offerid));
		comCapDto.setConsume_daily_payout_cap(conversionService.selectDailyCap(offerid));
		return new ResponseEntity<ConsumeCapDto>(comCapDto, HttpStatus.OK);
	}
	
}
